package ltd.smallwang.networkrecord.controller;

import cn.hutool.core.io.IoUtil;
import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.fastjson2.JSONObject;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import ltd.smallwang.networkrecord.dao.ApiRecordMapper;
import ltd.smallwang.networkrecord.entity.ApiRecord;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author justd
 * @description 功能描述
 * @since 2024-07-24 22:55
 **/
@RestController
@RequiredArgsConstructor
public class CommonController {

  private final ApiRecordMapper apiRecordMapper;

  @RequestMapping("/api/record/{applicationName}")
  public SingleResponse<String> record(@PathVariable("applicationName") String applicationName,
      HttpServletRequest httpServletRequest) {
    ApiRecord apiRecord = new ApiRecord();
    apiRecord.setApplicationName(applicationName);
    Map<String, String> requestHeader = new HashMap<>();
    Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
    while (headerNames.hasMoreElements()) {
      String headerName = headerNames.nextElement();
      requestHeader.put(headerName, httpServletRequest.getHeader(headerName));
    }
    apiRecord.setRespHeader(JSONObject.toJSONString(requestHeader));
    if (HttpMethod.POST.name().equalsIgnoreCase(httpServletRequest.getMethod())) {
      try (ServletInputStream inputStream = httpServletRequest.getInputStream()) {
        String requestBody = IoUtil.read(inputStream, StandardCharsets.UTF_8);
        apiRecord.setRespBody(requestBody);
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
    }
    apiRecord.setCreateTime(LocalDateTime.now());
    apiRecordMapper.insert(apiRecord);
    return SingleResponse.of("success");
  }

  @GetMapping("/api/record/query")
  public SingleResponse<List<ApiRecord>> getCommonResult(
      @RequestParam("applicationName") String applicationName) {
    List<ApiRecord> apiRecords = apiRecordMapper.queryByApplicationName(applicationName);
    return SingleResponse.of(apiRecords);
  }
}
